/**
 * Created by spatra on 14-12-3.
 */

define(['projectJS/module'], function(projectModule){

  projectModule.factory('ProjectService', ['ResourceService', function(ResourceService){
    return{
      accessor: ResourceService.getResourceAccessor({ resourceName: 'project' }),
      //返回所有的项目，包括加入的和自己创建的
      getAllProjects: function(){
        var self = this;

        return self.accessor.get({
          params: {
            per_page: 100,
            page: 1,
            option: 'all'
          }
        })
          .then(function(resp){
            return resp.data.data;
          }, function(resp){
            alert('项目列表加载出错');
            console.error(resp.data);
          });
      },
      getCreaterAndMembers: function(projectId){
        var self = this;

        return self.accessor.show(projectId)
          .then(function(resp){
            var rtn = resp.data.members || [];
            rtn.push( resp.data.creater );

            return rtn;
          }, function(resp){
            console.error(resp);
            alert('加载项目成员信息失败!');
          });
      }
    };
  }]);

  projectModule.factory('TaskService', ['$cacheFactory', '$rootScope', 'NestedResourceService', 'DatetimeHelperService', 'PaginationService', 'ClassHelperService',
    function($cacheFactory, $rootScope, NestedResourceService, DatetimeHelperService, PaginationService, ClassHelperService){
      //缓存对象应该是在此处生成，而不是每次调用方法时生成
      var showCacheObj = $cacheFactory('taskCache', { capacity: 10 });

      //过滤方法组成的集合，key对应过滤方法名，value为对应的过滤函数，函数的参数包括：待检测对象、条件
      var filterMethods = {
        'priority_id': function(checkObj, cond){
          return checkObj['priority_id'] == cond;
        },
        'datetimes': function(checkObj, cond){
          return DatetimeHelperService.checkRange(checkObj['expected_at'], cond);
        }
      };

      return {
        accessor: NestedResourceService.getResourceAccessor({
          parentResourceName: 'project',
          nestedResourceName: 'task'
        }),
        showWithCache: function(taskId){
          return this.accessor.show(taskId, {
            cache: showCacheObj
          });
        },
        finished: function(taskId){
          return this.accessor.update(taskId, {
            status: 'finished'
          });
        },
        getTaskSetWithPagination: function(stateParams, statusList){
          var self = this;
          self.accessor['setParentResourceId'](stateParams);

          function getLabelIdSet(statusList){
            var labelIdSet = {};
            for(var i=0; i<statusList.length; i++){
              labelIdSet[statusList[i].name] = statusList[i].id;
            }
            return labelIdSet;
          }

          var labelIdSet = getLabelIdSet(statusList);

          return self.accessor.get({
            params: {
              per_page: 18,
              page: 1,
              group: true
            }
          })
            .then(function(resp){
              return self.divideTaskByStatus( resp.data, labelIdSet );
            }, function(data){
              $rootScope.$emit('message:error',{
                title: '获取任务列表失败',
                msg: data.error
              });
            });
        },

        divideTaskByStatus: function(sourceTasks, labelIdSet){

          var taskSet = {};

          for(var statusLabel in sourceTasks) {
            var taskSetByStatus = {};
            var statusId = labelIdSet[statusLabel];

            var taskStatusInfo = sourceTasks[statusLabel];

            taskSetByStatus.data = taskStatusInfo.data;

            var pagination = PaginationService.createPagination({
              type: 'LoadingPagination',
              currentPage: taskStatusInfo.current_page,
              itemsPerPage: taskStatusInfo.per_page,
              totalItems: taskStatusInfo.total
            });

            taskSetByStatus.pagination = pagination;

            taskSet[statusId] = taskSetByStatus;

          }
          return taskSet;

        },
        convertToCondItems: function(source, sourceCond, sourceLabel){
          var result = [];

          source.forEach(function(item){
            result.push({
              'cond': item[sourceCond],
              'label': item[sourceLabel]
            });
          });

          return result;
        },
        //根据条件动态生成过滤函数
        buildFiltersFun: function(condObj){
          
          return function(checkObj){
            for(var condItem in condObj ){
              if( ! filterMethods[ condItem ](checkObj, condObj[condItem]) ){
                return false;
              }
            }

            return true;
          };
        },
        filterTaskOnCond: function(source, condObj){
          var result = [], self = this;

          var filter = self.buildFiltersFun(condObj);
          source.forEach(function(item){
            if( filter(item) ){
              result.push(item);
            }
          });

          return result;
        },
        filterAndDividedByStatus: function(sourceTasks, condObj){
          var self = this, filteredSource = sourceTasks;

          if( ! ClassHelperService.isEmpty(condObj) ){
            filteredSource = self.filterTaskOnCond(sourceTasks, condObj);
          }

          return self.divideTaskByStatus(filteredSource);
        }
      };
  }]);

  projectModule.factory('MemberService', ['NestedResourceService', function(NestedResourceService){
    return {
      accessor: NestedResourceService.getResourceAccessor({
        parentResourceName: 'project',
        nestedResourceName: 'member'
      })
    };
  }]);

  projectModule.factory('RoleService', ['ResourceService', function(ResourceService){
    return {
      accessor: ResourceService.getResourceAccessor({
        'resourceName': 'role'
      })
    };
  }]);

  projectModule.factory('CommentService', ['NestedResourceService', function(NestedResourceService){
    return {
      accessor: NestedResourceService.getResourceAccessor({
        parentResourceName: 'project|discussion',
        nestedResourceName: 'comment'
      })
    };
  }]);

  /**
   * 方法 getStatusSet 会返回以Id为索引的类数组对象, 该对象以Promise对象形式封装
   */
  projectModule.factory('TaskStatusService', ['$rootScope', 'ResourceService', function($rootScope, ResourceService){
    return {
      accessor: ResourceService.getResourceAccessor({
        'resourceName': 'task-status'
      }),
      getStatusSet: function(){
        return this.accessor.get()
          .then(function(resp){
            var statusSet = {};

            resp.data.forEach(function(elem){
              statusSet[ elem.id ] = elem;
            });

            return statusSet;
          }, function(data){
            alert('出错：任务状态数据加载失败！');
            $rootScope.$emit('message:error', {
              title: '任务状态数据加载失败',
              msg: data.error
            });
          });
      }
    };
  }]);


  /**
   * TaskPriorityService 用于对获取或处理任务的优先级信息
   */
  projectModule.factory('TaskPriorityService', ['ResourceService', function(ResourceService) {
    return {
      accessor: ResourceService.getResourceAccessor({
        'resourceName': 'task-priority'
      })
    };
  }]);//End of --> TaskPriorityService

  /**
   * 此服务用于 项目-讨论 的获取和添加评论等操作
   */
  projectModule.factory('DiscussionService', ['$http', 'NestedResourceService',
    function($http, NestedResourceService){

      return {
        accessor: NestedResourceService.getResourceAccessor({
          parentResourceName: 'project',
          nestedResourceName: 'discussion'
        }),
        addComment: function(data, stateParams){
          var self = this;

          self.accessor['setParentResourceId'](stateParams);

          return $http.post([
            self.accessor.getBaseUrl(), stateParams['discussionId'], 'comment'
          ].join('/'), data);
        }
      };

  }]);//End of --> DiscussionService

  projectModule.factory('StatusScrollService', ['ScrollService', function(ScrollService){
    return {
      init: function(){
        var $statusPanel = angular.element.find('.status-panel');
        $statusPanel.each(function(){
          console.log($(this));
        });

      }
    };//End of --> return
  }]);//End of --> StatusScrollService

  projectModule.factory('ProjectSharingService', ['$window', 'NestedResourceService',
    function($window, NestedResourceService){

      return {
        accessor: NestedResourceService.getResourceAccessor({
          parentResourceName: 'project',
          nestedResourceName: 'sharing'
        }),
        getOnStartPaginationConf: function(stateParams){
          var self = this;

          self.accessor['setParentResourceId'](stateParams);

          return self.accessor.get({
            params: {
              per_page: 20,
              page: 1
            }
          });
        },
        getTempUploadUri: function(){
          return ['file', 'temp', 'resource'].join('/');
        },
        downloadResource: function(resourceId){
          var downloadUrl = ['api', 'file', 'resource-download', resourceId];
          $window.location = downloadUrl.join('/');
        }
      };
  }]);//End of --> ProjectSharingService

  projectModule.factory('ProjectTagService', ['NestedResourceService', function(NestedResourceService){
    return {
      accessor: NestedResourceService.getResourceAccessor({
        parentResourceName: 'project',
        nestedResourceName: 'tag'
      })
    };
  }]);//End of --> NestedResourceService
});